# oss 上传
import json
import logging
import oss2
import requests


endpoint = "oss-cn-shanghai.aliyuncs.com"
bucket_name = "ad-web-scraper"
logger = logging.getLogger("oss")

class MyOssError(Exception):
    def __init__(self, message):
        super().__init__(message)
        self.message = message

oss_upload_exception = MyOssError("OSS upload error")
oss_delete_exception = MyOssError("OSS delete error")
oss_download_exception = MyOssError("OSS download error")

class OSSManager:
    def __init__(self, token:dict):
        self.auth = oss2.StsAuth(token["access_key_id"], token["access_key_secret"],token["security_token"])

    def upload_user_response(self, date,request_id,mid,response):
        bucket = oss2.Bucket(self.auth, endpoint, bucket_name)
        json_str = json.dumps(response, indent=4, ensure_ascii=False)
        json_bytes = json_str.encode("utf-8")
        result = bucket.put_object(f"bilibili/users/{date}/{request_id}/{mid}.json", json_bytes,
                                   headers={"Content-Type": "application/json"})
        if result.status != 200:
            raise oss_upload_exception

    def upload_video_response(self, date,request_id,bvid,response):
        bucket = oss2.Bucket(self.auth, endpoint, bucket_name)
        json_str = json.dumps(response, indent=4, ensure_ascii=False)
        json_bytes = json_str.encode("utf-8")
        result = bucket.put_object(f"bilibili/posts/{date}/{request_id}/{bvid}.json", json_bytes,
                                   headers={"Content-Type": "application/json"})
        if result.status != 200:
            raise oss_upload_exception

    def delete_file(self, endpoint, bucket, file_path):
        bucket = oss2.Bucket(self.auth, endpoint, bucket)
        result = bucket.delete_object(file_path)
        if result.status != 204:
            raise oss_delete_exception
    def download_file(self, endpoint, bucket, file_path, file_path_local):
        bucket = oss2.Bucket(self.auth, endpoint, bucket)
        result = bucket.get_object_to_file(file_path, file_path_local)
        if result.status != 200:
            raise oss_download_exception


def get_token():
    retries = 0
    while retries < 3:
        try:
            headers ={
                "Content-Type": "application/json",
                "oma-user": "spider",
            }
            json = {
                "role": "acs:ram::1493683880260647:role/ad-web-scraper",
                "expiretime": "3600",
            }
            response = requests.get("https://ad-yunwei-tools.lilith.com/get-sts-token", headers=headers,json=json,timeout=5)
            if response.status_code == 200:
                logger.info("oss获取token成功")
                logger.info(f"token:{response.json()}")
            else:
                logger.error(f"oss获取token失败,状态码:{response.status_code}")
                logger.error(f"响应内容:{response.json()}")
            return response.json()
        except Exception as e:
            retries += 1

def upload_user_response(date,request_id,mid,response):
    token = get_token()
    auth = oss2.StsAuth(token["access_key_id"], token["access_key_secret"],token["security_token"])
    bucket = oss2.Bucket(auth, endpoint, bucket_name)
    json_str = json.dumps(response, indent=4, ensure_ascii=False)
    json_bytes = json_str.encode("utf-8")
    result = bucket.put_object(f"bilibili/users/{date}/{request_id}/{mid}.json", json_bytes,headers={"Content-Type": "application/json"})
    print("文件保存到:"+f"bilibili/users/{date}/{request_id}/{mid}.json")
    if result.status != 200:
        raise oss_upload_exception


